package com.yizhiliulianta.user.designPattern.filterPattern;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArticleFilterFactory implements InitializingBean {

    @Resource
    private List<IArticleFilter> iArticleFilterList;

    private static final Map<ArticleFilterEnum,IArticleFilter> handlerMap = new HashMap<>();

    public static List<IArticleFilter> createArticleFilter(List<ArticleFilterEnum> articleFilterEnumList){
        List<IArticleFilter> articleFilterList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(articleFilterEnumList)){
            for (ArticleFilterEnum articleFilterEnum : articleFilterEnumList){
                IArticleFilter filter = createFilter(articleFilterEnum);
                articleFilterList.add(filter);
            }
        }
        return articleFilterList;
    }

    public static IArticleFilter createFilter(ArticleFilterEnum articleFilterEnum){
        return handlerMap.get(articleFilterEnum);
    }

    public static List<ArticleFilterEnum> getFilterList(){
        List<ArticleFilterEnum> filterEnumList = new ArrayList<>();;
        for (Map.Entry<ArticleFilterEnum,IArticleFilter> filterEntry : handlerMap.entrySet()){
            ArticleFilterEnum key = filterEntry.getKey();
            filterEnumList.add(key);
        }
        return filterEnumList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (IArticleFilter iArticleFilter : iArticleFilterList) {
            handlerMap.put(iArticleFilter.getArticleFilter(),iArticleFilter);
        }
    }
}
